using System;
using System.Collections;
using System.Collections.Generic;
using EchoFramework;
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 通用黑背景
/// </summary>
public class CommonBlackBg : MonoBehaviour
{
    private Image commonBlackBg;

    /// <summary>
    /// 黑色
    /// </summary>
    private readonly Color BlackColor = new Color(0, 0, 0, 200f / 255f);

    /// <summary>
    /// 无色
    /// </summary>
    private readonly Color EmptyColor = new Color(0, 0, 0, 0);

    /// <summary>
    /// 父级的UIView
    /// </summary>
    private UIViewBase parentUIView;

    /// <summary>
    /// 记录目前已生成的黑背景字典
    /// Key:UIPanelTypeEnum枚举
    /// Value:CommonBlackBg列表
    /// </summary>
    private static Dictionary<UIPanelTypeEnum, List<CommonBlackBg>> recordCommonBlackBgDict = new Dictionary<UIPanelTypeEnum, List<CommonBlackBg>>();

    private void Awake()
    {
        commonBlackBg = GetComponent<Image>();
        parentUIView = GetComponentInParent<UIViewBase>();
    }

    private void Start()
    {
        if (parentUIView == null)
        {
            GameLogger.LogWarning("通用黑色背景无父级UIViewBase");
            return;
        }

        UIPanelTypeEnum panelEnum = parentUIView.ViewCfg.PanelTypeEnum;
        if(!recordCommonBlackBgDict.ContainsKey(panelEnum))
            recordCommonBlackBgDict.Add(panelEnum, new List<CommonBlackBg>());
        recordCommonBlackBgDict[panelEnum].Add(this);
        commonBlackBg.color = EmptyColor;  //默认显示空
        RefreshBlackBg();
    }

    /// <summary>
    /// 刷新黑背景
    /// </summary>
    private void RefreshBlackBg()
    {
        bool showBlack = true;
        for (int i = (int)UIPanelTypeEnum.Max - 1; i > 0; i--)
        {
            if (recordCommonBlackBgDict.TryGetValue((UIPanelTypeEnum) i, out List<CommonBlackBg> tempCommonBlackBgList))
            {
                for (int j = tempCommonBlackBgList.Count - 1; j >= 0; j--)
                {
                    CommonBlackBg tempCommonBlackBg = tempCommonBlackBgList[j];
                    tempCommonBlackBg.commonBlackBg.color = showBlack ? BlackColor : EmptyColor;
                    showBlack = false;
                }
            }
        }
    }
    
    private void OnDestroy()
    {
        if (parentUIView == null)
        {
            return;
        }
        UIPanelTypeEnum panelEnum = parentUIView.ViewCfg.PanelTypeEnum;
        recordCommonBlackBgDict[panelEnum].Remove(this);
        RefreshBlackBg();
    }
}